
app.factory("$localStorage", ["$window", "$q", "$timeout", function ($window, $q, $timeout) {
    function LocalStorageProvider() {
    };

    LocalStorageProvider.prototype.set = function (key, value) {
        return $timeout(function () {
            if (!value) $q.reject("No object to store in cache.");
            var str = JSON.stringify(value);
            $window.localStorage.setItem(key, str);
        });
    };

    LocalStorageProvider.prototype.get = function (key) {
        return $timeout(function () {
            var str = $window.localStorage.getItem(key);
            if (str == null) return null;
            //console.log("get", key, "from cache");
            return JSON.parse(str);
        });
    };

    LocalStorageProvider.prototype.getAll = function (query) {
        return $timeout(function () {
            var list = [];
            for (var key in $window.localStorage) {
                //console.log("getAll match", query, key);
                if (!query || key.match(query)) {
                    //console.log("getAll match result ok");
                    var str = $window.localStorage.getItem(key);
                    list.push(JSON.parse(str));
                }
            }
            return list;
        });
    };

    LocalStorageProvider.prototype.count = function (query) {
        return $timeout(function () {
            var count = 0;
            for (var key in $window.localStorage) {
                //console.log("count match", query, key);
                if (!query || key.match(query)) {
                    //console.log("count match result ok");
                    count = count + 1;
                }
            }
            return count;
        });
    };

    LocalStorageProvider.prototype.remove = function (key) {
        return $timeout(function () {
            delete $window.localStorage[key];
            console.log("remove", key, "from cache");
        });
    };

    return new LocalStorageProvider();
} ]);